#version 130

in vec3 LightDirectionTangent;
in vec3 Position;
in vec3 Normal;
in vec4 TexCoord;
in vec4 ShadowCoord;

uniform vec3 Kd; // Diffuse reflectivity
uniform vec3 Ld; // Light source intensity

uniform sampler2D Tex1;
uniform sampler2D normalMap;
uniform sampler2DShadow shadowMap;

out vec4 FragColor;

varying vec3 tangentSurface2light;
varying vec3 tangentSurface2view;

vec2 poissonDisk[16] = vec2[]( 
   vec2( -0.94201624, -0.39906216 ), 
   vec2( 0.94558609, -0.76890725 ), 
   vec2( -0.094184101, -0.92938870 ), 
   vec2( 0.34495938, 0.29387760 ), 
   vec2( -0.91588581, 0.45771432 ), 
   vec2( -0.81544232, -0.87912464 ), 
   vec2( -0.38277543, 0.27676845 ), 
   vec2( 0.97484398, 0.75648379 ), 
   vec2( 0.44323325, -0.97511554 ), 
   vec2( 0.53742981, -0.47373420 ), 
   vec2( -0.26496911, -0.41893023 ), 
   vec2( 0.79197514, 0.19090188 ), 
   vec2( -0.24188840, 0.99706507 ), 
   vec2( -0.81409955, 0.91437590 ), 
   vec2( 0.19984126, 0.78641367 ), 
   vec2( 0.14383161, -0.14100790 ) 
);

// Returns a random number based on a vec3 and an int.
float random(vec3 seed, int i){
	vec4 seed4 = vec4(seed,i);
	float dot_product = dot(seed4, vec4(12.9898,78.233,45.164,94.673));
	return fract(sin(dot_product) * 43758.5453);
}


void main() 
{
	
	// The diffuse shading equation
	vec2 coordUV = vec2(TexCoord.x, TexCoord.y);
	vec3 texColor = vec3(texture( Tex1, coordUV ));

	vec3 TextureNormal_tangentspace = normalize(texture( normalMap, coordUV ).rgb*2.0 - 1.0);
	vec3 LightIntensity =  Ld * Kd * max(dot( tangentSurface2light, TextureNormal_tangentspace ),0.0);

	float visibility=1.0;

	// Fixed bias
	float bias = 0.005;

	// Sample the shadow map 4 times
	for (int i=0;i<4;i++){
		visibility -= 0.2*(1.0-texture( shadowMap, vec3(ShadowCoord.xy + poissonDisk[i]/700.0,  (ShadowCoord.z-bias)/ShadowCoord.w) ));
	}

	FragColor  = vec4 (texColor * visibility * LightIntensity * 0.7, 1.0);
}